<template>
  <div class="directory-tree">
    <!-- 搜索框 -->
    <el-input
      v-model="searchKey"
      placeholder="请输入目录名称"
      clearable
      prefix-icon="el-icon-search"
      style="margin-bottom: 10px;"
    />

    <!-- 目录树 -->
    <el-tree
      ref="tree"
      :data="treeData"
      :props="treeProps"
      :filter-node-method="filterNode"
      node-key="id"
      default-expand-all
      @node-click="handleNodeClick"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <!-- 节点名称 -->
          <el-tooltip
            :content="node.label"
            placement="top"
            effect="dark"
          >
            <span class="node-label">{{ node.label }}</span>
          </el-tooltip>
          <!-- 操作按钮 -->
          <el-dropdown
            v-if="showActionDropdown(data)"
            trigger="click"
            style="margin-left: 10px;"
            @command="(cmd) => handleDropdownCommand(cmd, node, data)"
          >
            <i class="el-icon-more" style="cursor: pointer;" />
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="isFixedSecondLevel(data)" command="add">新增目录</el-dropdown-item>
              <el-dropdown-item v-if="isThirdLevel(data)" command="edit">编辑</el-dropdown-item>
              <el-dropdown-item v-if="isThirdLevel(data)" command="delete">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </span>
      </template>
    </el-tree>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form :model="form" label-width="120px">
        <!-- 所属资源目录 -->
        <el-form-item label="所属资源目录">
          <el-input
            v-model="form.parentName"
            :disabled="true"
            style="background: #f5f7fa;"
          />
        </el-form-item>
        <!-- 目录名称 -->
        <el-form-item label="目录名称" prop="label">
          <el-input
            v-model="form.label"
            placeholder="请输入目录名称"
            @blur="form.label = form.label.trim()"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDeptsBm } from '@/api/system/dept'
import { updateDataNode, getAddinsert, getDeleteNode } from '@/api/system/dept'
import { Message } from 'element-ui'

export default {
  name: 'DirectoryTree',
  data() {
    return {
      treeData: [],
      treeProps: {
        children: 'CMeunDepts',
        label: 'name'
      },
      searchKey: '',
      dialogVisible: false,
      dialogTitle: '',
      form: {
        label: '',
        id: '',
        parentId: '',
        parentName: '',
        dataType: 0
      }
    }
  },
  computed: {
    filteredTreeData() {
      if (!this.searchKey) return this.treeData
      const filter = (data) => {
        return data.reduce((acc, item) => {
          const children = item.CMeunDepts ? filter(item.CMeunDepts) : []
          if (item.name.includes(this.searchKey) || children.length > 0) {
            acc.push({ ...item, CMeunDepts: children })
          }
          return acc
        }, [])
      }
      const a = filter(this.treeData)
      console.log('aaaaa', this.treeData, a)
      return a
    }
  },
  watch: {
    searchKey(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.fetchTreeData()
  },
  methods: {
    filterNode(value, data, node) {
      if (!value) return true
      if (data.name) {
        return this.chooseNode(value, data, node)
      }
    },
    // 过滤父节点 / 子节点
    chooseNode(value, data, node) {
      if (data.name.indexOf(value) !== -1) {
        return true
      }
      const level = node.level
      // 如果传入的节点本身就是一级节点就不用校验了
      if (level === 1) {
        return false
      }
      // 先取当前节点的父节点
      let parentData = node.parent
      // 遍历当前节点的父节点
      let index = 0
      while (index < level - 1) {
        // 判断匹配中英文过滤
        if (parentData.data.name.indexOf(value) !== -1) {
          return true
        }
        // 否则的话再往上一层做匹配
        parentData = parentData.parent
        index++
      }
      // 没匹配到返回false
      return false
    },
    async fetchTreeData() {
      try {
        const res = await getDeptsBm()
        if (!res || res.name !== '数据目录' || !res.id) { // 校验顶级节点id
          throw new Error('后端返回数据格式异常，缺少顶级节点ID')
        }

        const topLevelNode = { ...res, level: 1, isTopLevel: true }
        if (topLevelNode.CMeunDepts && topLevelNode.CMeunDepts.length > 0) {
          topLevelNode.CMeunDepts = topLevelNode.CMeunDepts.map(secondNode => {
            // 校验二级节点id
            if (!secondNode.id) {
              Message.warning('发现无效二级目录（缺少ID），已自动过滤')
              return null // 标记为无效节点
            }
            const handledSecond = { ...secondNode, level: 2, parentName: topLevelNode.name }

            // 校验三级节点id
            if (handledSecond.CMeunDepts) {
              handledSecond.CMeunDepts = handledSecond.CMeunDepts
                .filter(thirdNode => thirdNode.id) // 过滤无id的三级节点
                .map(thirdNode => ({
                  ...thirdNode, level: 3, parentName: handledSecond.name
                }))
            }
            return handledSecond
          }).filter(Boolean) // 移除无效的二级节点
        }
        this.treeData = [topLevelNode]
      } catch (error) {
        Message.error('获取目录数据失败，请稍后重试')
        console.error('Directory data error:', error)
      }
    },

    showActionDropdown(data) {
      return data.level === 2 || data.level === 3
    },

    // 2. 删除右键菜单处理方法 handleNodeContextMenu
    // handleNodeContextMenu(event, node, data) { ... },

    handleNodeClick(node) {
      console.log('点击节点：', node)
      this.$emit('node-click', node)
    },

    handleDropdownCommand(cmd, node, data) {
      cmd === 'add' ? this.handleAdd(data) : cmd === 'edit' ? this.handleEdit(data) : this.handleDelete(data)
    },

    isFixedSecondLevel(data) {
      return data.level === 2 && (data.parentName === '数据目录' || data.parentId === this.treeData[0]?.id)
    },

    isThirdLevel(data) {
      return Number(data.level) === 3
    },

    handleAdd(data) {
      if (!data || !this.isFixedSecondLevel(data)) return

      this.dialogTitle = '新增目录'
      this.form = {
        label: '',
        parentId: data.id,
        parentName: data.name,
        dataType: data.dataType,
        id: ''
      }
      this.dialogVisible = true
    },

    handleEdit(data) {
      if (!data || !data.id || !this.isThirdLevel(data)) {
        Message.warning('编辑失败：未获取到有效目录ID')
        return
      }

      this.dialogTitle = '编辑目录'
      this.form = {
        label: data.name,
        id: data.id, // 确保id已存在
        parentId: data.parentId,
        parentName: data.parentName,
        dataType: data.dataType
      }
      this.dialogVisible = true
    },

    // 删除目录：参数改为直接接收 data，移除右键菜单关闭逻辑
    async handleDelete(data) {
      if (!data || !this.isThirdLevel(data)) return

      this.$confirm('此操作将永久删除该目录，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          // 调用删除接口
          console.log(data.id, '删除节点ID')
          await getDeleteNode(data.id) // 简化：无需接收response（原代码未使用）

          // 执行前端删除操作
          const removeNode = (treeData, nodeId) => {
            for (let i = 0; i < treeData.length; i++) {
              if (treeData[i].id === nodeId) {
                treeData.splice(i, 1)
                return true
              }
              if (treeData[i].CMeunDepts && removeNode(treeData[i].CMeunDepts, nodeId)) {
                return true
              }
            }
            return false
          }

          const isRemoved = removeNode(this.treeData, data.id)
          if (isRemoved) {
            Message.success('删除成功！')
          } else {
            Message.warning('删除失败：未找到该节点')
          }
        } catch (error) {
          console.error('删除接口调用失败：', error)
          Message.error('删除失败，请稍后重试')
        }
      }).catch(() => {
        Message.info('已取消删除')
      })
    },

    // 提交表单（新增/编辑）：逻辑不变，无需依赖右键菜单数据
    async submitForm() {
      if (!this.form.label.trim()) {
        Message.warning('请输入目录名称')
        return
      }

      if (this.dialogTitle === '编辑目录' && !this.form.id) {
        Message.error('编辑失败：缺少目录ID，请刷新后重试')
        return
      }

      const requestData = {
        id: this.form.id,
        name: this.form.label,
        parentId: this.form.parentId,
        parentName: this.form.parentName,
        dataType: this.form.dataType
      }

      try {
        if (this.dialogTitle === '新增目录') {
          await getAddinsert(requestData)
          await this.fetchTreeData()
          Message.success('新增目录成功！')
          this.dialogVisible = false
        } else {
          console.log('编辑接口请求参数:', requestData)
          await updateDataNode(requestData)
          const isUpdated = this.updateNodeInTree(this.treeData, requestData.id, requestData.name)

          if (isUpdated) {
            Message.success('编辑目录成功！')
            this.dialogVisible = false
            setTimeout(() => {
              this.fetchTreeData()
            }, 500)
          } else {
            throw new Error('编辑成功，但本地目录更新失败，请手动刷新')
          }
        }
      } catch (error) {
        console.error('操作失败：', error)
        Message.error(error.message || `${this.dialogTitle === '新增目录' ? '新增' : '编辑'}目录失败，请稍后重试`)
      }
    },

    // 更新树中的节点名称：逻辑不变
    updateNodeInTree(data, nodeId, newName) {
      for (const item of data) {
        if (item.id === nodeId) {
          item.name = newName
          return true
        }
        if (item.CMeunDepts && this.updateNodeInTree(item.CMeunDepts, nodeId, newName)) {
          return true
        }
      }
      return false
    }
  }
}
</script>

<style scoped>
.directory-tree {
  padding: 10px;
}

.custom-tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.el-input.is-disabled .el-input__inner {
  color: #606266;
}

.node-label {
  /* width: 80px; */
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
